﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EasyMvc.Web.Common;
using EasyMvc.Models;
using EasyMvc.Controls;
using EasyMvc.Core;
using EasyMvc.Utility;

namespace EasyMvc.Web.Areas.MWeb.Controllers
{
    [Permission(EnumViewPermission.ManageUser)]
    public class UserController : MWebControllerBase
    {
        #region Actions
        [AuthorizeIgnore]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AuthorizeIgnore]
        public ActionResult Login(User user)
        {
            if (ModelState.IsValid)
            {
                if (!object.Equals(this.MHttpContext.VerifyCode, Request["VerifyCode"]))
                {
                    ModelState.AddModelError("VerifyCode", "验证码错误");
                    return View(user);
                }

                string pwd = Encrypt.MD5(user.Password.Trim());
                var currentUser = DbContext.Users.SingleOrDefault(u => u.Username == user.Username && u.Password == pwd);
                if (currentUser != null)
                {
                    this.MHttpContext.UserName = currentUser.Username;
                    return RedirectToAction("HomePage");
                }
                else
                {
                    ModelState.AddModelError("OtherError", "用户名或密码错误");
                    return View(user);
                }
            }

            return View(user);
        }
        [AuthorizeIgnore]
        public ActionResult Logout()
        {
            this.MHttpContext.RemoveUserCookie();
            return RedirectToAction("Login");
        }

        [AuthorizeIgnore]
        public ActionResult VerifyImage()
        {
            ValidateCodeType s1 = new ValidateCode_Style4();
            string code;
            byte[] bytes = s1.CreateImage(out code);
            this.MHttpContext.VerifyCode = code;
            return File(bytes, @"image/jpeg");
        }

        public ActionResult HomePage()
        {
            return View();
        }

        public ActionResult Index(User model, int id = 1)
        {
            IQueryable<User> queryList = this.DbContext.Users;

            if (!string.IsNullOrEmpty(model.Username))
                queryList = queryList.Where(u => u.Username.Contains(model.Username));

            var result = queryList.OrderByDescending(u => u.AddTime).ToPagedList(id, this.PageSize);

            return View(result);
        }

        //
        // GET: /Home/Edit/5

        public ActionResult Edit(string id)
        {
            var model = this.DbContext.Users.Find(id);

            RenderViewData(model);

            return View(model);
        }

        //
        // POST: /Home/Edit/5

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            if (!ModelState.IsValid)
                return View();

            var model = this.DbContext.Users.Find(id);
            this.TryUpdateModel<User>(model);
            model.RoleIds = collection["RoleIds"];

            this.DbContext.SaveChanges();

            return this.RefreshParent();
        }

        //
        // GET: /Home/Create

        public ActionResult Create()
        {
            var model = new User();
            RenderViewData(model);

            return View("Edit", model);
        }

        //
        // POST: /Home/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            var model = new User();
            this.TryUpdateModel<User>(model);

            model.Password = "111111";
            model.AddTime = DateTime.Now;
            model.Password =  Encrypt.MD5(model.Password);
            model.RoleIds = collection["RoleIds"];

            this.DbContext.Users.Add(model);
            this.DbContext.SaveChanges();

            return this.RefreshParent();
        }

        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            var ids = collection["ids"].Split(',');
            ids.ToList().ForEach(id => this.DbContext.Users.Remove(this.DbContext.Users.Find(id)));
            this.DbContext.SaveChanges();

            return RedirectToAction("Index");
        }

        public ActionResult ModifyPwd()
        {
            var model = new User();
            model.Username = this.UserContext.User.Username;
            return View(model);
        }

        [HttpPost]
        public ActionResult ModifyPwd(FormCollection collection)
        {
            var model = this.DbContext.Users.Find(this.UserContext.User.Username);
            model.Password = Encrypt.MD5(collection["Password"]);

            this.DbContext.SaveChanges();

            return this.RefreshParent();
        }

        private void RenderViewData(User model)
        {
            var roles = this.DbContext.Roles.ToList();
            foreach (var role in roles)
            {
                if (!string.IsNullOrEmpty(role.Description))
                    role.Name = string.Format("{0}({1})", role.Name, role.Description);
            }

            this.ViewData.Add("RoleIds", new SelectList(roles, "Id", "Name", model.RoleIds));
        }

        #endregion
    }
}
